import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { Login } from '@/api/user'
import { useRouterStore } from '@/store/router'

// 用户基本信息
export const useUserInfoStore = defineStore(
  'UserInfo',
  () => {
    const { getRouter } = useRouterStore()
    const router = useRouter()
    const userInfo = ref({})
    // 修改用户基本信息
    const changeUserInfo = value => {
      userInfo.value = value
    }
    // 登陆
    const loginHandel = async req => {
      const { data, msg, success } = await Login(req)
      if (success) {
        userInfo.value = data
        message.success('登陆成功')
        await getRouter()
        router.push('/home')
      } else {
        message.error(msg)
      }
      // localStorage.setItem('token', data.token);
    }

    // 退出登陆
    const logoutHandel = () => {
      userInfo.value = {}
      // localStorage.removeItem('token');
      sessionStorage.clear()
      router.push('/login')
    }

    return {
      userInfo,
      changeUserInfo, //
      loginHandel,
      logoutHandel
    }
  },
  { persist: true }
)
